package com.flyaudio.xiaopengautopilot.util;
import android.content.Context;
import android.util.Log;

import com.flyaudio.xiaopengautopilot.db.DBManager;

import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class JSONUtil {
    private static final String TAG = "JSONUtil";

    public static final  String fileDir = "/storage/emulated/0/FlyCarMsg/iFlyPC/"; //文件夹路径
    public static final String fileName = "flyaudio.json";
    private static JSONUtil instance = new JSONUtil();
    private JSONObject obj = null;
    private Context context = null;
    private JSONUtil(){

    }
    private void initJSONUtil(){
        try {
            String path = context.getDatabasePath(fileName).getAbsolutePath();
            String str = getJSONData(path);
            if(str != null) {
                Log.d(TAG, "initJSONUtil: "+str);
                L.d(TAG,str);
                obj = new JSONObject(str);
            }else {
                L.d(TAG,"json data is null");

                System.out.println(TAG + " json data is null");
                obj = new JSONObject();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private  void saveJSONData(JSONObject jsonObject){

        String path = context.getDatabasePath(fileName).getAbsolutePath();
        File file = new File(path);
        Writer writer = null;
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            file.setWritable(true);


            FileOutputStream outputStream = new FileOutputStream(file,false);
            outputStream.write(jsonObject.toString().getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void updateJson(String key,Object val){
        try {
            if(obj == null){
                L.d(TAG,"json data no init");
                return;
            }
            obj.put(key,val);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        saveJSONData(obj);
    }

    public String getJSONData(String path) {
        try {
            File file = new File(path);
            if (file.isFile() && file.exists()) {
                InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
                BufferedReader br = new BufferedReader(inputStreamReader);
                StringBuilder builder = new StringBuilder();
                String line = br.readLine();
                while (line != null) {
                    builder.append(line);
                    line = br.readLine();
                }
                br.close();
                inputStreamReader.close();
                return builder.toString();
            }
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            System.out.println("Cannot find the file specified!");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Error reading file content!");
            e.printStackTrace();
        }
        return null;
    }
    public Object getMileageJSON(String keyName,Object def) {

        try {
            if(obj == null){
                L.d(TAG,"json data no init");
                return def;
            }
            if (obj.has(keyName))
                return obj.get(keyName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return def;
    }

    public static JSONUtil getInstance() {
        return instance;
    }

    public void init(Context context) {
        this.context = context;
        FileOpenPatch task  = new FileOpenPatch(new FileOpenPatch.TaskCallback() {
            @Override
            public void run() {
                initJSONUtil();
            }
        });
    }
}
